﻿using System;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Net;
using System.Reflection;
using System.Windows.Forms;
using pub.NET20Fix;

namespace todo
{
    public partial class FrmAbout : Form
    {
        private volatile bool closing;

        public FrmAbout()
        {
            InitializeComponent();
            this.Font = SystemFonts.MessageBoxFont;
            //
            this.Text = "About " + App.Title;
            pictureBox1.Image = App.MainForm.Icon.ToBitmap();

            //
            var assembly = Assembly.GetExecutingAssembly();
            var attributes = assembly.GetCustomAttributes(typeof (AssemblyCopyrightAttribute), false);
            var copyright = ((AssemblyCopyrightAttribute) attributes[0]).Copyright;

            attributes = assembly.GetCustomAttributes(typeof (AssemblyCompanyAttribute), false);
            var company = ((AssemblyCompanyAttribute) attributes[0]).Company;

            lblName.Text = App.Title;// +" v" + App.Version;
            lblName.Font = new Font(this.Font.FontFamily, 16, FontStyle.Bold);
            lblVersion.Text = App.Version;

            lblCopyright.Text = copyright + " " + company;

            lnkEmail.LinkColor = lnkSite.LinkColor = Color.FromArgb(0, 102, 204);

            Localize();
        }

        private void Localize()
        {
#if zh
            this.Text = "关于" + App.Title;
            lblCopyright.Text = "版权所有 © 2013 newzera";
            btnCheckUpdate.Text = "检查更新";
            lnkEmail.Text = "电子邮件：newzera@163.com";
            lnkSite.Text = "项目主页: http://todoexe.codeplex.com";
#endif
        }

        private void lnkEmail_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            var command = lnkEmail.Text.Replace(" ", "");
            try
            {
                Process.Start("mailto:newzera@163.com");
            }
            catch (Exception ex)
            {
                var title = "Failed to launch mail client";
#if zh
                title = "无法启动邮件客户端";
#endif
                MessageBox.Show(ex.Message, title,
                        MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

        private void lnkSite_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Process.Start("http://todoexe.codeplex.com");
        }

        private void btnCheckUpdate_Click(object sender, EventArgs e)
        {
            btnCheckUpdate.Tag = btnCheckUpdate.Text;
            btnCheckUpdate.Text = "Checking for updates...";
#if zh
            btnCheckUpdate.Text = "检查更新中...";
#endif
            btnCheckUpdate.Enabled = false;
            var url = "http://todoexe.codeplex.com/wikipage?title=version";
            var req = WebRequest.Create(url);
            req.BeginGetResponse(ar => {
                if (this.closing)
                {
                    return;
                }
                var rsp = req.EndGetResponse(ar);
                string text;
                using (var reader = new StreamReader(rsp.GetResponseStream()))
                {
                    text = reader.ReadToEnd();
                }
                rsp.Close();
                this.Invoke((Action) (() => CheckUpdate(text)));
            }, null);
        }

        private void CheckUpdate(string text)
        {
            if (this.closing)
            {
                return;
            }
            btnCheckUpdate.Text = (string) btnCheckUpdate.Tag;
            btnCheckUpdate.Enabled = true;

            var remoteVersion = ReadConfigValue(text, "todo.exe.version");
            if(remoteVersion == null)
            {
                return;
            }
            string msg;
            if (remoteVersion == App.Version)
            {
                msg = "Todo.EXE is up to date";
#if zh
                msg = "当前已是最新版本";
#endif
                MessageBox.Show(msg, App.Title, 
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            msg = "Latest version is " + remoteVersion + ", do you want to download it now?";
#if zh
            msg = "最新版本是" + remoteVersion + ", 现在下载吗？";
#endif
            var dr = MessageBox.Show(msg, 
                    App.Title, 
                    MessageBoxButtons.YesNo, 
                    MessageBoxIcon.Question);
                if (dr == DialogResult.No)
                {
                    return;
                }
                var downloadUrl = ReadConfigValue(text, "todo.exe.download.url");
                Process.Start(downloadUrl);
        }

        private static string ReadConfigValue(string text, string sKey)
        {
            var sFind = sKey + "=";
            var pos = text.IndexOf(sFind, StringComparison.Ordinal);
            if (pos == -1)
            {
                MessageBox.Show("something wrong while checking version info", "Oops");
                return null;
            }
            pos += sFind.Length;
            var pos2 = text.IndexOf('<', pos);
            var remoteVersion = text.Substring(pos, pos2 - pos);
            return remoteVersion;
        }

        private void FrmAbout_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.closing = true;
        }
    }
}